//
//  ZYPurchaseLogRecorder.m
//  Pods
//
//  Created by wu on 2020/9/15.
//

#import "ZYPurchaseLogRecorder.h"
#import "ZYPurchaseDataBase.h"

@interface ZYPurchaseLogRecorder ()

@property (nonatomic, copy) NSString *fileName;

@property (nonatomic, strong) NSMutableArray *logContent;

@end

@implementation ZYPurchaseLogRecorder

+ (instancetype)genLogRecorder{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
    NSString *fileName = [dateString stringByAppendingString:@".txt"];
    ZYPurchaseLogRecorder *logRec = [[ZYPurchaseLogRecorder alloc] initWithFileName:fileName];
    return logRec;
}

- (instancetype)initWithFileName:(NSString *)fileName{
    self = [super init];
    if (self) {
        self.fileName = fileName;
        
        self.logContent = @[].mutableCopy;
    }
    return self;
}

- (void)record:(id)content{
    if (!content) {
        return;
    }
    if ([content isKindOfClass:[NSString class]] ||
        [content isKindOfClass:[NSDictionary class]] ||
        [content isKindOfClass:[NSArray class]]) {
        [self.logContent addObject:content];
    }
    [self finish];
}

- (NSString *)logFilePath{
    if (!self.fileName || (self.fileName.length == 0)) {
        return nil;
    }
    return [[ZYPurchaseDataBase logFileDirectoryPath] stringByAppendingPathComponent:self.fileName];
}

- (NSString *)formatContentToString:(NSArray *)contentArr {
    if (!contentArr ||
        ![contentArr isKindOfClass:[NSArray class]] ||
        (contentArr.count < 3)) {
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{@"log":contentArr} options:NSJSONWritingPrettyPrinted error:nil];
    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strJson;
}

- (BOOL)finish{
    NSString *filePath = [self logFilePath];
    if (filePath) {
        NSString *contentString = [self formatContentToString:self.logContent];
        if (contentString) {
            NSError *writeError;
            [contentString writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:&writeError];
            return writeError?NO:YES;
        }
    }
    return NO;
}

@end
